package com.passengerflowmanagementsystem.statistics.utils;

import com.intelligt.modbus.jlibmodbus.Modbus;
import com.intelligt.modbus.jlibmodbus.master.ModbusMasterFactory;
import com.intelligt.modbus.jlibmodbus.tcp.TcpParameters;
import com.intelligt.modbus.jlibmodbus.master.ModbusMaster;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ModbusMasterUtils {

    //获取连接
    public static ModbusMaster getModbusMaster(String ip, Integer port)  {
        try {
            TcpParameters tcpParameters = new TcpParameters();
            //ip
            InetAddress adress = InetAddress.getByName(ip);
            tcpParameters.setHost(adress);
            // TCP设置长连接
            tcpParameters.setKeepAlive(true);
            // TCP设置端口，这里设置是默认端口502
            tcpParameters.setPort(port);

            ModbusMaster master = ModbusMasterFactory.createModbusMasterTCP(tcpParameters);
            Modbus.setAutoIncrementTransactionId(true);
            return master;
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;

    }

    /**
     * 读04
     * @param master 配置的mater主机
     * @param slaveId 从机id
     * @param offset 寄存器读取开始地址  0059的话则为58
     * @param quantity 读取的寄存器数量
     * @return float类型的值
     */
    public static List<Float> readInputRegisters(ModbusMaster master, int slaveId, int offset, int quantity){
        List<Float> floatList=new ArrayList<>();
        try {

            if (!master.isConnected()) {
                master.connect();// 开启连接
            }

            // 读取对应从机的数据，readInputRegisters读取的写寄存器，功能码04
            int[] registerValues = master.readInputRegisters(slaveId, offset, quantity);

            floatList = ByteArrayConveter.getFloatArray(registerValues);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return floatList;
    }

    /**
     * 读03
     * @param master 配置的mater主机
     * @param slaveId 从机id
     * @param offset 寄存器读取开始地址  0059的话则为58
     * @param quantity 读取的寄存器数量
     * @return float类型的值
     */
    public static List<Float> readHoldingRegisters(ModbusMaster master,int slaveId,int offset,int quantity){
        List<Float> floatList=new ArrayList<>();
        try {

            if (!master.isConnected()) {
                master.connect();// 开启连接
            }

            // 读取对应从机的数据，readInputRegisters读取的写寄存器，功能码04
            int[] registerValues = master.readHoldingRegisters(slaveId, offset, quantity);

            floatList = ByteArrayConveter.getFloatArray(registerValues);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return floatList;
    }

    public static void close(ModbusMaster master){
        try {
            master.disconnect();

        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * byte数组转float数组
     * @param bytes
     * @return
     */
    public float[] bytesToFloats(byte[] bytes){
        float[] newFloat = new float[bytes.length/4];
        for (int i = 0; i < bytes.length/4; i++) {
            byte[] tmpBytes = Arrays.copyOfRange(bytes, i * 4, i * 4 + 4);
            Float tmpFloat = hexToFloat(bytesToHex(tmpBytes));
            newFloat[i] = tmpFloat;
        }
        return newFloat;
    }

    /**
     * 16进制字符串转float
     * @param hex
     * @return
     */
    public Float hexToFloat(String hex){
        return Float.intBitsToFloat( Integer.valueOf( hex, 16 ) );
    }

    /**
     * byte转16进制字符串
     * @param bytes
     * @return
     */
    public String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if(hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}

